package com.baorant.seckillfront.service;

//import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

//@Slf4j
@Service
public class TokensLimiter {	
	private final Logger log = LoggerFactory.getLogger(TokensLimiter.class);
	// 最后一次令牌发放时间
	public long timeStamp = System.currentTimeMillis();
	// 桶的容量
	public int capacity = 10;
	// 令牌生成速度10/s
	public int rate = 10;
	// 当前令牌数量
	public int tokens;

	public boolean acquire() {
	    long now = System.currentTimeMillis();
		// 当前令牌数
	    log.info( "now - timeStamp：" + (now - timeStamp));
		tokens = Math.min(capacity, (int) (tokens + (now - timeStamp) * rate / 1000));		
		log.info( "当前令牌数：" + tokens);
		timeStamp = now;
		if (tokens < 1) {
			// 若没有不到令牌,则拒绝
			log.info("限流了");
			return false;
		} else {
			// 还有令牌，领取令牌
			tokens--;
			log.info("剩余令牌=" + tokens);
		}
		return true;
	}
	
}
